package com.itheima.开启多线程.卖票.解决线程安全问题方案.Lock锁对象;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 王加鑫
 * @Date 2021/5/22 14:56
 * @Version 1.0
 */
public class Ticket implements Runnable {
    //总共100张票
    private int ticket = 100;
    //创建Lock锁对象
    Lock lock = new ReentrantLock();

    //创建Lock锁对象

    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if(ticket <= 0){
                    break;
                }else {
                    Thread.sleep(10);
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "正在卖票,还剩下" + ticket + "张票");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }
}
